package cn.skyisazure.metacompare.other;

import cn.hutool.core.lang.Console;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Set;

/**
 * 多数据源动态加载、切换等工具类
 * @author wangjj
 * @date 2023/7/24 10:11
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class DynamicDatasourceUtil {

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;
    private final DefaultDataSourceCreator dataSourceCreator;

    /**
     * 获取当前的数据源名
     * @return
     */
    public String getCurrentDataSourcesPoolName(){
        return DynamicDataSourceContextHolder.peek();
    }

    /**
     * 获取所有数据源名
     * @return
     */
    public Set<String> getDataSourcePoolNames(){
        Map<String, DataSource> dataSources = dynamicRoutingDataSource.getDataSources();
        Console.log(dataSources);
        return dataSources.keySet();
    }

    /**
     * 获取所有数据源名
     * @return
     */
    public Map<String, DataSource> getDataSources(){
        return dynamicRoutingDataSource.getDataSources();
    }

    /**
     * 添加数据源
     * <code><pre>
     * DruidConfig druidConfig = new DruidConfig();
     * // 连接池初始化时创建的连接数
     * druidConfig.setInitialSize(2);
     * // 最大连接数
     * druidConfig.setMaxActive(10);
     * // 连接池中最小空闲连接数
     * druidConfig.setMinIdle(5);
     * // 获取连接时的最大等待时间（毫秒）
     * druidConfig.setMaxWait(10000);
     * dataSourceProperty
     *         .setDruid(druidConfig) // 可默认，需要设置最大连接数时需要手动指定
     *         .setPoolName("数据源名")
     *         .setUrl("jdbc:mysql://localhost:3306/test-db?useUnicode=true&characterEncoding=utf-8")
     *         .setUsername("root")
     *         .setPassword("root")
     *         .setDriverClassName("com.mysql.cj.jdbc.Driver");
     * <pre/><code/>
     */
    public DataSource addDataSources(DataSourceProperty dataSourceProperty){
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
        return dataSource;
    }
    /**
     * 删除数据源
     * @param poolName
     */
    public void removeDataSources(String poolName){
        dynamicRoutingDataSource.removeDataSource(poolName);
    }

}
